<script setup>
import { getGraduateMyInfoService } from '@/api/graduate'
import {
  updateUserSecurityInfoService,
  userResetPasswordService,
  userUpdatePasswordService
} from '@/api/user'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
const router = useRouter()
const userStore = useUserStore()
const form = ref({
  phone: '',
  email: ''
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }]
}
const graduateInfo = ref({})
const getGraduateInfo = async () => {
  const res = await getGraduateMyInfoService()
  graduateInfo.value = res.data
  /**
   * 
   * {
  "graduateId": 6,
  "userId": 6,
  "nickName": "钰树临疯",
  "avatarUrl": "https://img2.baidu.com/it/u=4148564018,1930444022&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
  "employmentStatus": 1,
  "major": "生物医学",
  "college": "医学院",
  "graduationYear": 2025,
  "extendedInfo": {
      "personalIntro": "生物医学专业毕业生，擅长实验研究",
      "realName": "刘八",
      "gender": "男",
      "phone": 13467890123,
      "politicalStatus": "团员",
      "degree": "本科",
      "birthDate": "1997-09-05"
  },
  "employmentInfo": {
      "locationProvince": "北京市",
      "locationDetail": "中关村生命科学园",
      "locationCountry": "中国",
      "jobTitle": "医药研发员",
      "locationCity": "朝阳区"
  },
  "educationInfo": {
      "studyingAt": null,
      "graduateSchool": "北京大学",
      "degreeStatus": "Bachelor"
  },
  "createTime": "2025-02-20T01:27:00",
  "updateTime": "2025-04-05T13:57:34",
  "userName": "E02111122",
  "userRole": {
      "code": 2,
      "desc": "student"
  }
}
   */
  // console.log(graduateInfo.value);
  form.value = {
    password: '',
    phone: graduateInfo.value.extendedInfo.phone,
    email: graduateInfo.value.extendedInfo.email
  }
}
getGraduateInfo()
const showPasswordDialog = ref(false)
const showForgotPassword = ref(false)

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是 6-15 位的非空字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是 6-15 位的非空字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是 6-15 位的非空字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const passwordFormRef = ref(null)

// 修改密码
const handleUpdatePassword = async () => {
  console.log('修改密码', passwordForm.value)
  await passwordFormRef.value.validate()
  try {
    const { data } = await userUpdatePasswordService(passwordForm.value)

    ElMessage.success(data)
    showPasswordDialog.value = false
    // 清空修改密码表单
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
    // 提示用户需要重新登录
    ElMessage.info('密码修改成功，即将跳转到登录页面重新登录...')
    // 清除用户信息
    userStore.clearUser()

    // 1.5秒后跳转到登录页面
    setTimeout(() => {
      router.push('/login')
    }, 1500)
  } catch (error) {
    console.log(error)
    ElMessage.error('密码修改失败')
  }
}

const forgotForm = ref({
  newPassword: '',
  confirmPassword: ''
})

const forgotRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码格式不正确' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是 6-15 位的非空字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== forgotForm.value.newPassword) {
          callback(new Error('两次输入不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const forgotFormRef = ref(null)
// 重置密码
const handleResetPassword = async () => {
  console.log('重置密码', forgotForm.value)

  try {
    const { data } = await userResetPasswordService(forgotForm.value)
    console.log(data)
    ElMessage.success(data)
    // 清空重置密码表单
    forgotForm.value = {
      newPassword: '',
      confirmPassword: ''
    }

    // 提示用户需要重新登录
    ElMessage.info('密码重置成功，即将跳转到登录页面重新登录...')
    // 清除用户信息
    userStore.clearUser()

    // 1.5秒后跳转到登录页面
    setTimeout(() => {
      router.push('/login')
    }, 1500)
  } catch (error) {
    console.log(error)
    ElMessage.error('重置密码失败')
  }
}

const updatePhoneAndEmail = async () => {
  try {
    const { data } = await updateUserSecurityInfoService(form.value)
    console.log('信息', data)
    ElMessage.success(data)
    // 提示用户需要重新登录
    // ElMessage.info('修改成功');
  } catch (error) {
    console.log(error)
    ElMessage.error('修改失败')
  }
}
</script>

<template>
  <div class="settings-page">
    <h2 class="page-title">账号设置</h2>

    <el-form :model="form" :rules="rules" label-width="80px">
      <el-form-item label="密码" prop="password">
        <el-button type="primary" @click="showPasswordDialog = true">点击修改密码</el-button>
      </el-form-item>

      <!--  <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" maxlength="11" :autocomplete="'new-password'" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" type="email" />
      </el-form-item>-->

      <!-- <el-form-item>
        <el-button type="primary" @click="updatePhoneAndEmail">保存修改</el-button>
      </el-form-item>-->
    </el-form>
  </div>

  <el-dialog v-model="showPasswordDialog" :close-on-click-modal="false" title="密码管理" width="30%">
    <!-- 修改密码表单 -->
    <el-form v-if="!showForgotPassword" @submit.prevent :model="passwordForm" :rules="passwordRules"
      ref="passwordFormRef" label-position="right">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入当前密码" />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="6-15位非空字符" />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password
          @keyup.enter="handleUpdatePassword" placeholder="请再次输入新密码" />
      </el-form-item>

      <div class="dialog-footer">
        <el-button text type="primary" @click="showForgotPassword = true">忘记密码？</el-button>
        <el-button type="primary" @click="handleUpdatePassword">提交修改</el-button>
      </div>
    </el-form>

    <!-- 忘记密码表单 -->
    <el-form @submit.prevent label-position="right" v-else :model="forgotForm" :rules="forgotRules" ref="forgotFormRef">
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="forgotForm.newPassword" type="password" show-password placeholder="6-15位非空字符" />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="forgotForm.confirmPassword" type="password" show-password @keyup.enter="handleResetPassword"
          placeholder="请再次输入新密码" />
      </el-form-item>

      <div class="dialog-footer">
        <el-button text type="primary" @click="showForgotPassword = false">返回登录</el-button>
        <el-button type="primary" @click="handleResetPassword">重置密码</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.settings-page {
  .page-title {
    margin-bottom: 30px;
    color: #303133;
  }

  .el-form {
    max-width: 600px;
  }
}

.password {
  :deep(.el-input-group__append) {
    padding: 0 8px;
  }
}
</style>
